package control;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;

import model.object.ObjectUser;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.talknow.R;
import common.Const;

public class Screen5Activity extends Activity implements OnClickListener,
		Runnable {

	ObjectUser objUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_screen_5);
		try {
			objUser = (ObjectUser) getIntent().getExtras().getSerializable(
					Const.KEY_OBJECT);
			new Thread(this).start();
		} catch (Exception e) {
			// TODO: handle exception
		}
		((Button) findViewById(R.id.screen_5_button_nho))
				.setOnClickListener(this);
		((Button) findViewById(R.id.screen_5_button_target_change))
				.setOnClickListener(this);
		((Button) findViewById(R.id.screen_5_button_spec_change))
				.setOnClickListener(this);

		AdView adView = (AdView) this.findViewById(R.id.app_admob);
		AdRequest request = new AdRequest.Builder()
				.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
				.addTestDevice("9234EBAE83E894E6271DEBE7B380782E").build();
		adView.loadAd(request);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent;
		Bundle bundle;
		switch (v.getId()) {
		case R.id.screen_5_button_nho:
			finish();
			break;
		case R.id.screen_5_button_target_change:
			intent = new Intent(Screen5Activity.this, Screen2Activity.class);
			bundle = new Bundle();
			bundle.putSerializable(Const.KEY_OBJECT, objUser);
			intent.putExtras(bundle);
			startActivity(intent);
			break;
		case R.id.screen_5_button_spec_change:
			intent = new Intent(Screen5Activity.this, Screen3Activity.class);
			bundle = new Bundle();
			bundle.putSerializable(Const.KEY_OBJECT, objUser);
			intent.putExtras(bundle);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		// ServiceDelegate.getUserObject(objUser, mhandler);

		try {
			String userID = URLEncoder.encode(objUser.getUserid(), "UTF-8");
			final String BASE_URL = "http://doanhnghiepso.biz/server.php?userid="
					+ userID
					+ "&userapp="
					+ objUser.getUserapp()
					+ "&usersex="
					+ objUser.getUsersex()
					+ "&userage="
					+ objUser.getUserage()
					+ "&lat="
					+ objUser.getLat()
					+ "&lon="
					+ objUser.getLon()
					+ "&targetsex="
					+ objUser.getTargetsex()
					+ "&targetage="
					+ objUser.getTargetage()
					+ "&targetdistance="
					+ objUser.getTargetdistance();

			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(new HttpGet(BASE_URL));
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				response.getEntity().writeTo(out);
				out.close();
				String responseString = out.toString();
				if (!responseString.equals("[]")) {
					Log.i("Input", responseString.toString());
					JSONObject responseObj = new JSONObject(responseString);
					ObjectUser objUserResult = new ObjectUser();
					objUserResult.setUserapp(responseObj
							.getString(Const.KEY_USERAPP));
					objUserResult.setUserid(responseObj
							.getString(Const.KEY_USERID));
					objUserResult.setUsersex(responseObj
							.getString(Const.KEY_USERSEX));
					objUserResult.setUserage(responseObj
							.getString(Const.KEY_USERAGE));
					if (!objUserResult.getUserid().equals("")) {
						Intent intent = new Intent(Screen5Activity.this,
								Screen6Activity.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable(Const.KEY_OBJECT, objUserResult);
						intent.putExtras(bundle);
						Screen5Activity.this.startActivity(intent);
						Screen5Activity.this.finish();
					}
				} else {
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							Toast toat = Toast.makeText(getBaseContext(), "Not Found",
									Toast.LENGTH_SHORT);
							toat.setGravity(Gravity.CENTER, 0, 0);
							toat.show();
//							finish();
						}
					});
				}
			} else {
				// Closes the connection.
				response.getEntity().getContent().close();
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						Toast toat = Toast.makeText(getBaseContext(),
								"Server not responding", Toast.LENGTH_SHORT);
						toat.setGravity(Gravity.CENTER, 0, 0);
						toat.show();
//						finish();
					}
				});
				throw new IOException(statusLine.getReasonPhrase());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Toast toat = Toast.makeText(getBaseContext(), "Server not connect",
							Toast.LENGTH_SHORT);
					toat.setGravity(Gravity.CENTER, 0, 0);
					toat.show();
//					finish();
				}
			});
		}
	}
}
